use std::io::Read;
use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};
use std::sync::mpsc;

// 节流函数
fn throttle<F>(interval: Duration, f: F) -> impl FnMut()
where
    F: Fn() + Send + Sync + 'static,
{
    let f = Arc::new(f);
    // 使用 Arc 和 Mutex 共享状态
    let (sender, receiver) = mpsc::channel();
    let sender = Arc::new(Mutex::new(sender));

    // 创建一个线程来处理定时任务
    thread::spawn(move || {
        let f = Arc::clone(&f);

        let mut last_time = None;
        while let Ok(()) = receiver.recv() {
            let now = std::time::Instant::now();

            // 如果距离上次执行的时间小于 interval，则跳过
            if let Some(time) = last_time {
                if now.duration_since(time) < interval {
                    continue;
                }
            }

            // 更新上次执行时间并执行函数
            last_time = Some(now);
            f();
        }
    });

    // 返回一个闭包，用于触发节流函数
    move || {
        let sender = sender.lock().unwrap();
        sender.send(()).unwrap();
    }
}

fn main() {
    // 创建一个节流函数，间隔 500ms
    let mut throttled_print = throttle(Duration::from_millis(500), || {
        println!("Throttled: Hello, world!");
    });

    // 模拟高频触发
    for i in 0..10 {
        println!("Trigger: {}", i);
        throttled_print();
        thread::sleep(Duration::from_millis(100));
    }

    // 等待节流函数执行
    thread::sleep(Duration::from_secs(1));
}